package com.sanjiahantang.youjiaclient.module.evaluate.views.impl;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.sanjiahantang.uilibrary.popuwindow.SelectPhotoPopupwindow;
import com.sanjiahantang.uilibrary.utils.BitmapUtils;
import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.youjiaclient.R;
import com.sanjiahantang.youjiaclient.base.BaseMvpActivity;
import com.sanjiahantang.youjiaclient.base.BaseView;
import com.sanjiahantang.youjiaclient.config.ConfigValue;
import com.sanjiahantang.youjiaclient.module.common.beans.FileBean;
import com.sanjiahantang.youjiaclient.module.evaluate.adapters.GoodsEvaluateAdapter;
import com.sanjiahantang.youjiaclient.module.evaluate.beans.GoodsAppraiseInitResponse;
import com.sanjiahantang.youjiaclient.module.evaluate.presenters.MeEvaluatePresenter;
import com.sanjiahantang.youjiaclient.module.evaluate.views.MeEvaluateView;
import com.sanjiahantang.youjiaclient.module.goods.beans.GoodsBean;
import com.sanjiahantang.youjiaclient.module.me.order.beans.ShopListBean;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.util.List;

/**
 * Created by zy on 2017/10/28.
 */

public class EvaluateGoodsActivity extends BaseMvpActivity<MeEvaluateView,MeEvaluatePresenter> implements MeEvaluateView, View.OnClickListener {


    private RecyclerView recyclerView;
    private int goodsCurrentId;
    private GoodsEvaluateAdapter adapter;
    private String orderCode;
    private int busiId,position;
    private SelectPhotoPopupwindow photoPopupwindow;
    private View rootView;

    protected static final int CHOOSE_PICTURE = 0;
    protected static final int TAKE_PICTURE = 1;
    private static final int CROP_SMALL_PICTURE = 2;
    private static final int UPLOAD_PIC = 3;
    private static final int PHOTO_GRAPH = 0xF, SELECT_PICTURE = 3, INTENT_NICKNAME = 5, SAVE_PHOTO = 6;

    @Override
    public void loadData(RecyclerView.Adapter adapter) {

    }

    @Override
    public void showProgress() {
        super.showProgress($this);
    }

    @Override
    public MeEvaluatePresenter initPresenter() {
        return new MeEvaluatePresenter();
    }

    @Override
    public void initView() {
        setContentView(R.layout.activity_goods_evaluate);
        rootView = findViewById(R.id.rootView);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        findViewById(R.id.btnSubmit).setOnClickListener(this);
        findViewById(R.id.fl_Left).setOnClickListener(this);
        TextView title = (TextView) findViewById(R.id.title);
        title.setText("商品评价");
        Bundle b = getIntent().getBundleExtra(KEY_PARAM);
        ShopListBean.Data goods = (ShopListBean.Data) b.getSerializable("goods");
        orderCode = goods.getOrderCode();
        adapter = new GoodsEvaluateAdapter($this, new OnLoadListener() {
            @Override
            public void onLoad(Object content) {
                Object[] param = (Object[]) content;
                switch ((int)param[0]){
                    case CALLBACK_TYPE_ADD_PICTURE:
                        photoPopupwindow.showAtLocation(rootView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                        GoodsAppraiseInitResponse.Data bean = (GoodsAppraiseInitResponse.Data) param[1];
                        position = (int) param[2];
                        busiId = bean.getMaiId();
                        break;
                    case CALLBACK_TYPE_DELETE_PICTURE:
                        GoodsBean.Image img = (GoodsBean.Image) param[1];
                        presenter.deleteFile($this,img.getId(), position,new OnLoadListener() {
                            @Override
                            public void onLoad(Object content) {
                                Object[] param = (Object[]) content;
                                int id = (int) param[1];
                                int index = (int) param[2];
                                adapter.deleteImage(id,index);
                            }
                        });
                        break;
                }
            }
        });
        recyclerView.setAdapter(adapter);
        photoPopupwindow = new SelectPhotoPopupwindow($this, this);
    }

    @Override
    public void initData() {
        presenter.findGoodsAppraiseForCustomer($this,orderCode, new OnLoadListener() {
            @Override
            public void onLoad(Object content) {
                Object[] param = (Object[]) content;
                switch ((int)param[0]){
                    case CALLBACK_TYPE_GOODS_DETAIL:
                        List<GoodsAppraiseInitResponse.Data> list = (List<GoodsAppraiseInitResponse.Data>) param[1];
                        if (list != null){
                            for (GoodsAppraiseInitResponse.Data item : list) {
                                item.setOrderCode(orderCode);
                            }
                            adapter.setListData(list);
                        }else{
                            Utils.showToast($this,"数据获取错误");
                        }

                        break;
                }
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                takePicture();
            } else {
                Utils.showToast(this, "权限被禁止，相关功能无法使用！");
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK){
            switch (requestCode){
                case INTENT_SELECT_PIC:
                    Uri uri0 = data.getData();
                    presenter.doUploadGoodsEvaluate($this,uri0,busiId, new OnLoadListener() {
                        @Override
                        public void onLoad(Object content) {
                            FileBean.Data img = (FileBean.Data) content;
                            adapter.addImage(position,img);
                        }
                    });
                    break;
                case PHOTO_GRAPH:
                    if (data != null){
                        Bundle b = data.getExtras();
                        Bitmap bitmap = (Bitmap) b.get("data");
                        bitmap = BitmapUtils.resizeBitmap(bitmap, 480);
                        presenter.doUploadGoodsEvaluate($this, bitmap, busiId,new BaseView.OnLoadListener() {
                            @Override
                            public void onLoad(Object content) {
                                if (content != null && content instanceof FileBean.Data){
                                    FileBean.Data data = (FileBean.Data) content;
                                    adapter.addImage(position,data);
                                }
                            }
                        });
                    }else{
                        Utils.showToast($this,"请从相册选择图片");
                    }
                    break;
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btnSubmit:
                presenter.saveAppraiseForCustomer($this,adapter.getListData(), new OnLoadListener() {
                    @Override
                    public void onLoad(Object content) {
                        setResult(RESULT_OK);
                        finish();
                    }
                });
                break;
            case R.id.fl_Left:
                finish();
                break;
            //拍照
            case R.id.btn_take_photo:
                photoPopupwindow.dismiss();
                if (ContextCompat.checkSelfPermission($this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        requestPermissions(new String[]{Manifest.permission.CAMERA}, 1);
                    }
                } else {
                    takePicture();
                }
                break;
            //相册
            case R.id.btn_pick_photo:
                photoPopupwindow.dismiss();
                presenter.cardSelect($this);
                break;
        }
    }

    private void takePicture(){
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            try{
                startActivityForResult(takePhotoIntent, PHOTO_GRAPH);
            }catch (Exception e){
                e.printStackTrace();
                Utils.showToast($this,"请从相册上传图片");
            }
        } else
            Utils.showToast($this, "未插入SD卡");
    }
}
